package com.start.reggie.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){

        log.error(e.getMessage());

        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String username = split[2];
            return R.error("用户名" + username + "已存在");
        }
        return R.error("未知错误");

    }

    /**
     * 异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler
    public R<String> exceptionHandler(CustomException e){

        log.error(e.getMessage());

        return R.error(e.getMessage());

    }

}
